<template>
  <div class="title">news.publish</div>
  <div class="news-publish py-8">
    <!-- 步骤指示器 -->
    <div class="step-indicator flex justify-center mb-6">
      <div class="step-item">
        <div class="step-number bg-gray-200 text-gray-500 rounded-full w-8 h-8 flex items-center justify-center">
          <el-icon>
            <CircleCheckFilled />
          </el-icon>
        </div>
        <div class="step-label text-gray-500 ml-2">发布内容</div>
      </div>
      <div class="step-divider h-0.5 bg-gray-200 my-4" style="width: 200px;"></div>
      <div class="step-item active">
        <div class="step-number bg-blue-500 text-white rounded-full w-8 h-8 flex items-center justify-center">2</div>
        <div class="step-label ml-2">发布设置</div>
      </div>
    </div>

    <!-- 标题 -->
    <div class="form-title mb-2">
      <span class="required text-red-500">*</span>标题
    </div>
    <div class="form-content mb-6">
      <el-input v-model="ruleForm.name" placeholder="请输入新闻标题" maxlength="100" show-word-limit class="w-full" />
    </div>

    <!-- 封面和摘要 -->
    <div class="content-area mb-6">
      <div class="upload-section mb-4">
        <div class="section-label mb-2">
          <span class="required text-red-500">*</span>封面和摘要
        </div>
        <div class="upload-wrapper flex gap-6">
          <!-- 封面上传 -->
          <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1" :show-file-list="false"
            :on-change="handleChange" :before-upload="beforeUpload" class="cover-uploader">
            <template #default v-if="fileList.length === 0">
              <div class="upload-content flex flex-col items-center justify-center p-4 border-2 border-dashed rounded">
                <el-icon class="upload-icon text-gray-400 text-2xl mb-2">
                  <Plus />
                </el-icon>
                <div class="upload-text text-gray-500">上传图片</div>
                <div class="upload-hint text-xs text-gray-400 mt-1">建议尺寸480*200</div>
              </div>
            </template>
          </el-upload>

          <!-- 封面预览 -->
          <div v-if="fileList.length > 0" class="file-preview">
            <div v-for="file in fileList" :key="file.uid" class="file-container relative">
              <img class="cover-image w-40 h-20 object-cover rounded" :src="file.url" alt="封面图" />
              <span
                class="el-upload-list__item-actions absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 hover:opacity-100 transition-opacity">
                <span class="el-upload-list__item-preview text-white mr-4" @click="handlePictureCardPreview(file)">
                  <el-icon>
                    <ZoomIn />
                  </el-icon>
                </span>
                <span class="el-upload-list__item-delete text-white" @click="handleRemove(file)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </div>
          </div>

          <!-- 摘要输入 -->
          <div class="textarea-section flex-1">
            <el-input v-model="publishForm.issueDescription" type="textarea" placeholder="请输入新闻摘要（简要描述新闻内容）"
              class="summary-textarea w-full" :rows="4" />
          </div>
        </div>
      </div>
    </div>

    <!-- 发送时间 -->
    <div class="radio-section mb-8">
      <div class="section-label mb-2">
        <span class="required text-red-500">*</span>发送时间
      </div>
      <el-radio-group v-model="publishForm.pubway" class="radio-group flex items-center gap-6">
        <el-radio label="imediate" class="radio-item">立即发送</el-radio>
        <el-radio label="timed" class="radio-item">定时发送</el-radio>
        <!-- 定时时间选择（仅定时发送时显示） -->
        <div class="block" v-if="publishForm.pubway === 'timed'">
          <el-date-picker v-model="publishForm.waitPubTime" type="datetime" placeholder="选择定时发送时间" class="w-64"
            :disabled-date="(date: any) => date < new Date()" />
        </div>
      </el-radio-group>
    </div>

    <!-- 按钮区域 -->
    <div class="mt-8 flex justify-center gap-4">
      <el-button @click="gotoLast">上一步</el-button>
      <el-button type="primary" @click="handlePublish">发布</el-button>
    </div>
  </div>

  <!-- 图片预览弹窗 -->
  <el-dialog v-model="dialogVisible" title="封面预览" width="500px">
    <img :src="dialogImageUrl" alt="Preview Image" class="w-full" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { useRouter } from 'vue-router';
import { CircleCheckFilled, Delete, Plus, ZoomIn } from '@element-plus/icons-vue';
import type { UploadFile } from 'element-plus';
import { ElMessage, ElDialog } from 'element-plus';
import { newsIssueTemplate } from '@/api/newspublish';
import { newPublishReleaseList } from '@/api/newspool';
import { uploadApi } from '@/api/upload';
import { useUserinfo } from '@/stores/userinfo';

const user = useUserinfo().user;
const router = useRouter();
const dialogVisible = ref(false);
const dialogImageUrl = ref('');
const fileList = ref<UploadFile[]>([]);

const publishForm = reactive({
  issueTitle: '',
  pubway: 'imediate',
  waitPubTime: undefined,
  issueCoverImage: '',
  issueDescription: '',
  issuePublisher: user.username || 'admin',
});

const ruleForm = reactive({
  name: '',
  cover: '',
});

watch(
  () => ruleForm.name,
  (newTitle) => {
    publishForm.issueTitle = newTitle.trim();
  },
  { immediate: true }
);

newsIssueTemplate<{ template: string }>().then(res => {
  if (res.code === 200 && res.data.template) {
    ruleForm.name = res.data.template;
  }
}).catch(error => {
  console.error('加载标题模板失败:', error);
});

const handleChange = async (file: UploadFile) => {
  if (fileList.value.length >= 1) {
    ElMessage.warning('最多只能上传1张封面图片');
    return false;
  }

  const tempUrl = URL.createObjectURL(file.raw!);
  file.url = tempUrl;
  fileList.value = [file];
  ruleForm.cover = tempUrl;

  try {
    const formData = new FormData();
    formData.append('file', file.raw!);
    const uploadRes = await uploadApi(formData) as { code: number; data: { url: string }; message: string };

    if (uploadRes.code === 200 && uploadRes.data.url) {
      const baseUrl = import.meta.env.VITE_REQUEST_BASE_URL;
      const fullCoverUrl = baseUrl + uploadRes.data.url;

      file.url = fullCoverUrl;
      fileList.value = [file];
      publishForm.issueCoverImage = fullCoverUrl;

      setTimeout(() => {
        URL.revokeObjectURL(tempUrl);
      }, 1000);
    } else {
      throw new Error(uploadRes.message || '上传图片失败');
    }
  } catch (error: any) {
    console.error('封面上传失败:', error);
    ElMessage.error(error.message || '图片上传失败，请重试');
    fileList.value = [];
    ruleForm.cover = '';
    publishForm.issueCoverImage = '';
    if (file.url?.startsWith('blob:')) {
      URL.revokeObjectURL(file.url);
    }
  }

  return false;
};

const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG等图片格式！');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！');
    return false;
  }
  return true;
};

const handleRemove = (file: UploadFile) => {
  if (file.url?.startsWith('blob:')) {
    URL.revokeObjectURL(file.url);
  }
  fileList.value = fileList.value.filter(f => f.uid !== file.uid);
  publishForm.issueCoverImage = '';
  ruleForm.cover = '';
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

const gotoLast = () => {
  router.push('/newspublish');
};

const handlePublish = async () => {
  const validateResult = validatePublishForm();
  if (!validateResult.valid) {
    ElMessage.warning(validateResult.msg);
    return;
  }

  try {
    const publishRes = await newPublishReleaseList(publishForm) as { code: number; message: string };

    if (publishRes.code === 200) {
      ElMessage.success('新闻发布成功！');
      router.push('/newspublished');
    } else {
      throw new Error(publishRes.message || '发布失败');
    }
  } catch (error: any) {
    console.error('新闻发布失败:', error);
    ElMessage.error(error.message || '发布失败，请检查网络或联系开发人员');
  }
};

const validatePublishForm = (): { valid: boolean; msg: string } => {
  if (!publishForm.issueTitle.trim()) {
    return { valid: false, msg: '请填写新闻标题' };
  }
  if (!publishForm.issueCoverImage.trim()) {
    return { valid: false, msg: '请上传新闻封面' };
  }
  if (!publishForm.issueDescription.trim()) {
    return { valid: false, msg: '请填写新闻摘要' };
  }
  if (publishForm.pubway === 'timed' && !publishForm.waitPubTime) {
    return { valid: false, msg: '请选择定时发送时间' };
  }
  return { valid: true, msg: '校验通过' };
};
</script>

<style scoped>
.cover-image {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.upload-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.summary-textarea {
  width: 100%;
  min-height: 100px;
}

.radio-group {
  display: flex;
  align-items: center;
  gap: 20px;
}

.required {
  color: #ef4444;
  margin-right: 2px;
}

.form-title,
.section-label {
  font-weight: 500;
  color: #333;
}
</style>

<style scoped>
.title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.step-indicator {
  display: flex;
  align-items: center;
}

.step-item {
  display: flex;
  align-items: center;
}

.step-number {
  margin-right: 8px;
}

.active .step-label {
  color: #111827;
}

.step-divider {
  margin: 0 16px;
}

.step-item:not(.active) .step-number {
  background-color: #e5e7eb;
  color: #9ca3af;
}

.step-item:not(.active) .step-label {
  color: #9ca3af;
}

.upload-wrapper {
  position: relative;
  display: inline-block;
}

.file-preview {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.file-container {
  width: 100%;
  height: 100%;
  position: relative;
  border-radius: 6px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.el-upload-list__item-actions {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s;
}

.file-container:hover .el-upload-list__item-actions {
  opacity: 1;
}

.el-upload-list__item-actions span {
  cursor: pointer;
  color: white;
  margin: 0 8px;
}

/* 表单样式 */
.form-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.form-content {
  max-width: 600px;
  margin: 0 auto 20px;
}

.content-area {
  display: flex;
  max-width: 600px;
  margin: 0 auto 20px;
  gap: 16px;
}

.upload-section {
  width: 240px;
}

.textarea-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 52px;
}

.section-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #f56c6c;
  margin-right: 4px;
}

.cover-uploader {
  width: 240px;
  height: 180px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.upload-content {
  text-align: center;
}

.upload-icon {
  font-size: 24px;
  color: #8c939d;
}

.upload-text {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.upload-hint {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.file-container {
  width: 100%;
  height: 100%;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.summary-textarea {
  height: 180px;
}

.radio-section {
  max-width: 600px;
  margin: 0 auto 20px;
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-item {
  margin-right: 0;
}

.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
  min-width: 300px;
}

.demo-datetime-picker .block:last-child {
  border-right: none;
}

.demo-datetime-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .demo-datetime-picker .block {
    flex: 100%;
    border-right: none;
    border-bottom: solid 1px var(--el-border-color);
  }

  .demo-datetime-picker .block:last-child {
    border-bottom: none;
  }

  :deep(.el-date-editor.el-input) {
    width: 100%;
  }

  :deep(.el-date-editor.el-input__wrapper) {
    width: 100%;
    max-width: 300px;
  }
}
</style>